package com.mibus.mibusmobile;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;

import android.util.Log;

public class JSONParser {

    public JSONParser() {
    }

    public static JSONArray getJSONfromURL(String url){
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget= new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            String jsonResult = inputStreamToString(entity.getContent()).toString();
            JSONArray mArray = new JSONArray(jsonResult);
            return mArray;
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
            return null;
        }
    }

    public static StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        try{
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return answer;
    }
}